package com.mc.web;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mc.model.Department;
import com.mc.model.Lab;
import com.mc.model.Major;
import com.mc.model.Path;
import com.mc.model.ResearchLab;
import com.mc.model.Teacher;
import com.mc.model.Teachertype;
import com.mc.model.Teteacherytpe;
import com.mc.model.User;
import com.mc.service.IDepartmentService;
import com.mc.service.ILabService;
import com.mc.service.IResearchLabService;
import com.mc.service.MajorService;
import com.mc.service.TeacherService;
import com.mc.service.TeachertypeService;
import com.mc.service.TeteachertypeService;
import com.mc.utils.PathUtil;
import com.mc.utils.StringUtil;
import com.mc.utils.StringUtil2;

@Controller
@RequestMapping("/backend")
public class TeacherAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(TeacherAction.class);
   
	@Autowired private TeachertypeService teachertypeService;
	@Autowired private TeteachertypeService teteachertypeService;
	@Autowired private TeacherService teacherService;
	@Autowired private MajorService majorService;
	@Autowired private IResearchLabService labService;
	@Autowired private ILabService iLabService;
	@Autowired private IDepartmentService departmentService;
	private Path path = null;
	/**
	 * 
	 * @param modelMap
	 * @return  添加教师的界面
	 */
	@RequestMapping("/addteacherui")
	public String addTeacherui(ModelMap modelMap)
	{
		List<Major> majors = majorService.selectAllMajors();
		List<Teachertype> teachertypes = teachertypeService.selectAllTtypes();
		//logger.info(teachertypes.toString());
		List<ResearchLab> labs = labService.selectAllResearchLab();
		modelMap.addAttribute("labs",labs);
		modelMap.addAttribute("teachertypes", teachertypes);
		List<Lab> ilabs = iLabService.selectalllab();
		modelMap.addAttribute("ilabs", ilabs);
		modelMap.addAttribute("majors",majors);
		List<Department> departments = departmentService.selectalldepartment();
		modelMap.addAttribute("departments", departments);
		path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:addteacher","ViewTitle:添加老师","smenu:teachermag","mmenu:addteachers"});		
        
		return PathUtil.returnStr(path, modelMap);
	}
	
	/**
	 * 
	 * @param belong 教师类别
	 * @param modelMap 
	 * @param teacher 教师基本信息
	 * @param majorid 专业id
	 * @param session 
	 * @param researchlaId1  研究所id
	 * @param files 图片
	 * @param labId1 实验室id
	 * @param branch  
	 * @return 成功则返回见识管理界面
	 */
	@RequestMapping("/addteacher")
	public String addTeacher(@RequestParam("belong")String belong,ModelMap modelMap,Teacher teacher,
			@RequestParam("major1")int majorid,HttpSession session,
			@RequestParam("researchlaId1") int researchlaId1,@RequestParam(value = "fileste", 
			required = false) MultipartFile [] files,@RequestParam("labId1")int labId1,@RequestParam("branch1")int branch)
	{
		//System.out.println(teacher.toString());
		Map<String,Object> params = null;
		String imagePaths=uploadFiels(files);
		teacher.setPic(imagePaths);
		Lab lab = new Lab();
	    if(labId1!=0){
	    	lab.setLabId(labId1);
	    }else{
	    	lab.setLabId(null);
	    }
	    teacher.setLabId(lab);
	    Department department = new Department();
	    if(branch!=0){
	    	department.setdId(branch);
	    }else{
	    	department.setdId(null);
	    }
		int result = 0;
		Major major = new Major();
		ResearchLab rlab = new ResearchLab();
		if(majorid!=0)
		{
			major.setId(majorid);
			
		}else{
			major.setId(null);
		}
		if(researchlaId1!=0){
			rlab.setResearchlabId(researchlaId1);
		}else{
			rlab.setResearchlabId(null);
		}
		
		params = this.setParameter(teacher.getName(),
				teacher.getNo(),
				teacher.getGender(),
				major.getId(), 
				teacher.getPhone(),
				teacher.getQq(),
				((User)session.getAttribute("user")).getId(),
				teacher.getIntroduce(),
				teacher.getAchievement(),
				teacher.getProject(),
				teacher.getDirection(),
				rlab.getResearchlabId(),
				result,
				imagePaths,
				lab.getLabId() ,
				teacher.getPosition(),
				teacher.getOfficeLocation(),
				department.getdId());
		teacherService.insertTeacher(params);
		//System.out.println(params.get("result") + "-----resyuklt");
		Teacher teacher1 = teacherService.selectByPrimaryKey((Integer) params.get("result"));
		String [] id = belong.split(",");
		for(String id1:id){
			if(id1!=null && !id1.equals("0") && !id1.equals("")){
				Teachertype teteacherytpe = teachertypeService.selectByPrimaryKey(Integer.parseInt(id1));
				Teteacherytpe record = new Teteacherytpe();
				record.settId(teacher1);
				record.setTtypeId(teteacherytpe);
				teteachertypeService.insert(record );
			}
			
		}
		modelMap.addAttribute("message",true);
		return "forward:/backend/teachermagui";
	}
	/**
	 * 
	 * @param files 要进行上传的图片文件
	 * @return 上传照片的路径
	 */
		public String uploadFiels(MultipartFile[] files) {
			String imagepath = "";
			for (MultipartFile file : files) {
				if (file.isEmpty())
					continue;
				else {
					imagepath = com.mc.utils.UploadUtil.getInstance().upload(
							file,
							StringUtil2.getInstance()
									.getPhysicsPath("/images/books"));
					
				}
			}
			return imagepath;
		}
		
		
	public HashMap<String,Object> setParameter(String NAME1, String NO1, String gender1,
			Integer major_id1, String phone1, String qq1,
			Integer userid, String intro, String achievement1, String project1,
			String direction1, Integer researchlaid1, int result,String pic1,Integer labid1,
			String position,String officeLocation1,Integer branch1){
		HashMap<String,Object> params = new HashMap<String,Object>();
		params.put("NAME1", NAME1);
		params.put("NO1", NO1);
		params.put("gender1", gender1);
		params.put("major_id1", major_id1);
		params.put("phone1", phone1);
		params.put("qq1", qq1);
		params.put("userid", userid);
		params.put("intro", intro);
		params.put("achievement1", achievement1);
		params.put("project1", project1);
		params.put("direction1", direction1);
		params.put("researchlaid1", researchlaid1);
		params.put("pic1", pic1);
		params.put("labid1", labid1);
		params.put("result", result);
		params.put("position", position);
		params.put("officeLocation1", officeLocation1);
		params.put("branch1", branch1);
		return params;
	}
	/**
	 * 
	 * @param modelMap
	 * @return 教师管理界面
	 */
	@RequestMapping("/teachermagui")
	public String teachermag( ModelMap modelMap)
	{
		
		List<Department> departments = departmentService.selectalldepartment();
		List<List<Teacher>> teachers = new ArrayList<List<Teacher>>();
		for(Iterator<Department> iterator=departments.iterator();iterator.hasNext();){
			Department department = iterator.next();
			//logger.info(department.getdId());
			List<Teacher> teacher = teacherService.selectbydid(department.getdId());
			//logger.info(teacher.toString());
			teachers.add(teacher);
		}
		
		//logger.info(departments.size());
		//logger.info(teachers.get(1).toString());
		modelMap.addAttribute("departments", departments);
		modelMap.addAttribute("teachers", teachers);
		List<Teachertype> types = teachertypeService.selectAllTtypes();
		List<List<Teacher>> teachers1 = new ArrayList<List<Teacher>>();
		for(Iterator<Teachertype> iterator=types.iterator();iterator.hasNext();){
			Teachertype type = iterator.next();
			//logger.info(department.getdId());
			List<Teacher> teacher = new ArrayList<Teacher>();
			List<Teteacherytpe> teteacher = teteachertypeService.selectallteacherteachertype(type.getId());
			//logger.info(teacher.toString());
			for(Iterator<Teteacherytpe> it = teteacher.iterator();it.hasNext();){
				Teteacherytpe teteacherytpe = it.next();
				teacher.add(teteacherytpe.gettId());
			}
			
			teachers1.add(teacher);
		}
		//logger.info(departments.size());
		//logger.info(teachers.get(1).toString());
		modelMap.addAttribute("types", types);
		modelMap.addAttribute("teachers1", teachers1);
       path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:shiziduiwu","ViewTitle:教师管理","smenu:teachermag","mmenu:teachermag"});		
        
		return PathUtil.returnStr(path, modelMap);
	}
	/**
	 * 
	 * @param ids 教师id
	 * @param session
	 * @param request 
	 * @return 跨域ajax删除教师
	 */
	@RequestMapping("delteachers")
	@ResponseBody
	public String deleteteagher(@RequestParam("id")String ids,HttpSession session,HttpServletRequest request)
	{
		//logger.info(ids);
		User user = (User)session.getAttribute("user");
		String [] id = ids.split(",");
		for(String id1:id)
		{
			if(!id1.equals(""))
			{
			
				teacherService.del_teacher(new Integer(id1), user.getId());
			}
		}
		 String callbackFunName = request.getParameter("callbackparam");
		 
		 return callbackFunName +"("+ "{'success':true}" +")";
		
	}
	/**
	 * 
	 * @param id 更新教师的is
	 * @param modelMap
	 * @return 更新教师
	 */
	@RequestMapping("/updateteacher/{id}")
	public String updateTeacher(@PathVariable("id")int id,ModelMap modelMap){
		
		List<Major> majors = majorService.selectAllMajors();
		List<Teachertype> teachertypes = teachertypeService.selectAllTtypes();
		//logger.info(teachertypes.toString());
		List<ResearchLab> labs = labService.selectAllResearchLab();
		modelMap.addAttribute("labs",labs);
		modelMap.addAttribute("teachertypes", teachertypes);
		List<Lab> ilabs = iLabService.selectalllab();
		modelMap.addAttribute("ilabs",ilabs);
		modelMap.addAttribute("majors",majors);
		List<Department> departments = departmentService.selectalldepartment();
		modelMap.addAttribute("departments", departments);
	   Teacher teacher =teacherService.selectByPrimaryKey(id);
	  //logger.info(teacher.toString());
	   if(teacher.getResearchlaId()==null){
		   ResearchLab lab = new ResearchLab();
		   teacher.setResearchlaId(lab);
	   }
	   
	   if(!teacher.getIntroduce().equals("")){
		   teacher.setIntroduce(StringUtil.getInstace().zy(teacher.getIntroduce()));
	   }
	   modelMap.addAttribute("teacher",teacher);
	   
	   List<Teachertype> teachertypes2 = teachertypeService.selectteachertypeidbytid(teacher.getId());
	   modelMap.addAttribute("ts",teachertypes2);
	  
       path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:updateteacher","ViewTitle:修改教师信息","smenu:teachermag","mmenu:updateteachers"});		
        
		return PathUtil.returnStr(path, modelMap);
	}
	
	/**
	 * 
	 * @param belong  教师类型
	 * @param modelMap 
	 * @param teacher 教师基本西你想
	 * @param majorid 专业is
	 * @param session 
	 * @param researchlaId1  研究所id
	 * @param files 为教师头像
	 * @param labId1 实验室id
	 * @param branch
	 * @return 教师管理界面
	 */
	@RequestMapping("/updateteacher")
	public String updateteacher(@RequestParam("belong")String belong,ModelMap modelMap,Teacher teacher,
			@RequestParam("major1")int majorid,HttpSession session,@RequestParam("researchlaId1") int researchlaId1,
			@RequestParam(value = "fileste", 
			required = false) MultipartFile [] files,@RequestParam("labId1")int labId1,@RequestParam("branch1")int branch){
		//logger.info(teacher.toString());
		Teacher teacher1;
		String imagePaths=uploadFiels(files);
		//logger.info(imagePaths.length());
		if(!imagePaths.equals("") && imagePaths.length()!=0)
		{
			//logger.info("----test");
			teacher.setPic(imagePaths);
		}else{
			
			 teacher1 =teacherService.selectByPrimaryKey(teacher.getId());
			// logger.info(teacher1.toString());
			 teacher.setPic(teacher1.getPic());
		}
		Department department = new Department();
	    if(branch!=0){
	    	department.setdId(branch);
	    }
		Major major = null;
		ResearchLab lab = null;
		Lab ilab = new Lab();
		if(labId1!=0){
			ilab.setLabId(labId1);
		}
		if(majorid!=0)
		{
			major = majorService.selectByPrimaryKey(majorid);
			if(researchlaId1!=0){
				lab = labService.selectByPrimaryKey(researchlaId1);
			}else{
				
				lab = new ResearchLab();
				lab.setResearchlabId(null);
			}
		}else{
			major = new Major();
			major.setId(null);
			if(researchlaId1!=0){
				lab = labService.selectByPrimaryKey(researchlaId1);
			}else{
				lab = new ResearchLab();
				lab.setResearchlabId(null);
			}
		}
		teacher.setMajorId(major);
		teacher.setResearchlaId(lab);
		teacher.setLabId(ilab);
		teacher.setBranch(department);
		int result = teacherService.updateByPrimaryKey(teacher);
		
		//logger.info(result + ";;;;-----" +belong);
		teteachertypeService.deleteBytid(teacher.getId());
		String [] id = belong.split(",");
		for(String id1:id){
			if(id1!=null && !id1.equals("0") && !id1.equals("")){
				Teachertype teteacherytpe = teachertypeService.selectByPrimaryKey(Integer.parseInt(id1));
				Teteacherytpe record = new Teteacherytpe();
				record.settId(teacher);
				record.setTtypeId(teteacherytpe);
				teteachertypeService.insert(record );
			}
			
		}
		return "forward:/backend/teachermagui";
	}
	

}
